package com.macro.mall.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.github.pagehelper.PageHelper;
import com.macro.mall.common.api.CommonPage;
import com.macro.mall.common.api.CommonResult;
import com.macro.mall.dao.*;
import com.macro.mall.dto.*;
import com.macro.mall.mapper.*;
import com.macro.mall.model.*;
import com.macro.mall.service.PmsProductService;
import com.macro.mall.service.UmsAdminService;
import com.macro.mall.service.UmsStoreService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 商品管理Service实现类
 */
@Service
public class PmsProductServiceImpl implements PmsProductService {
    private static final Logger LOGGER = LoggerFactory.getLogger(PmsProductServiceImpl.class);
    @Autowired
    private PmsProductMapper productMapper;
    @Autowired
    private PmsMemberPriceDao memberPriceDao;
    @Autowired
    private PmsMemberPriceMapper memberPriceMapper;
    @Autowired
    private PmsProductLadderDao productLadderDao;
    @Autowired
    private PmsProductLadderMapper productLadderMapper;
    @Autowired
    private PmsProductFullReductionDao productFullReductionDao;
    @Autowired
    private PmsProductFullReductionMapper productFullReductionMapper;
    @Autowired
    private PmsSkuStockDao skuStockDao;
    @Autowired
    private PmsSkuStockMapper skuStockMapper;
    @Autowired
    private PmsProductAttributeValueDao productAttributeValueDao;
    @Autowired
    private PmsProductAttributeValueMapper productAttributeValueMapper;
    @Autowired
    private CmsSubjectProductRelationDao subjectProductRelationDao;
    @Autowired
    private CmsSubjectProductRelationMapper subjectProductRelationMapper;
    @Autowired
    private CmsPrefrenceAreaProductRelationDao prefrenceAreaProductRelationDao;
    @Autowired
    private CmsPrefrenceAreaProductRelationMapper prefrenceAreaProductRelationMapper;
    @Autowired
    private PmsProductDao productDao;
    @Autowired
    private PmsProductVertifyRecordDao productVertifyRecordDao;
    @Autowired
    private UmsAdminService umsAdminService;
    @Autowired
    private PmsCombinedProductMapper pmsCombinedProductMapper;
    @Autowired
    private UmsStoreService storeService;
    @Autowired
    private UmsStoreMapper umsStoreMapper;
    @Autowired
    private PmsProductVertifyRecordMapper pmsProductVertifyRecordMapper;
    @Autowired
    private SmsHomeRecommendProductMapper recommendProductMapper;
    @Autowired
    private PmsKeywordMapper keywordMapper;
    @Autowired
    private PmsSkuStockMapper pmsSkuStockMapper;
    @Autowired
    private PmsCombinedProductDao pmsCombinedProductDao;
    @Autowired
    private PmsSkuPriceLogMapper priceLogMapper;


    @Override
    public Long create(UmsAdminDTO admin, PmsProductParam productParam) {
        //如果获取的admin是空，给门店id
        if (admin.getStoreId() == null) {
            UmsStoreExample storeExample = new UmsStoreExample();
            storeExample.createCriteria().andUserIdEqualTo(admin.getId());
            List<UmsStore> umsStores = umsStoreMapper.selectByExample(storeExample);
            if(!CollectionUtils.isEmpty(umsStores)){
                admin.setStoreId(umsStores.get(0).getId());
            }
        }
        //创建商品
        PmsProduct product = productParam;
        //add by 高强 2020年9月4日
        //查看店铺上传商品是否需要审核
        UmsStore store = storeService.selectByPrimaryKey(admin.getStoreId());
        if (store.getAuditStatus() == 1) {
            //发布商品无需审核，新建商品verify_status字段置为1
            product.setVerifyStatus(1);//审核状态：0->未审核；1->审核通过
        } else {
            //发布商品需要审核，新建商品verify_status字段置为0，为0时商品不能上架
            product.setVerifyStatus(0);
        }
        //end add
        product.setMemberId(admin.getId());
        product.setMemberUserName(admin.getUserName());
        product.setStoreId(admin.getStoreId());
        product.setId(null);
        if (CollectionUtils.isEmpty(productParam.getPmsCombinedProductList())) {
            product.setType(0);
        } else {
            product.setType(1);
            productParam.getSkuStockList().clear();
            PmsSkuStockMemberPrice sku = new PmsSkuStockMemberPrice();
            productParam.getSkuStockList().add(sku);
        }
        String productSn = addProductSn(productParam.getProductSn(),admin.getStoreId());
        product.setProductSn(productSn);
        productMapper.insertSelective(product);
        //根据促销类型设置价格：会员价格、阶梯价格、满减价格
        Long productId = product.getId();

//        //阶梯价格
//        relateAndInsertList(productLadderDao, productParam.getProductLadderList(), productId, admin);
//        //满减价格
//        relateAndInsertList(productFullReductionDao, productParam.getProductFullReductionList(), productId, admin);
        //处理sku的编码
        handleSkuStockCode(productParam.getSkuStockList(), productId);
        //添加sku库存信息
        //如果是组合商品，给默认规格加上价格
        if (productParam.getType() != null && productParam.getType().equals(1)) {
            productParam.getSkuStockList().get(0).setPrice(productParam.getPrice());
        }
        List<PmsSkuStockMemberPrice> pmsSkuStockMemberPriceList = productParam.getSkuStockList();
        if (CollectionUtils.isEmpty(pmsSkuStockMemberPriceList)) {
            return -2L;
        }
        if (pmsSkuStockMemberPriceList != null && pmsSkuStockMemberPriceList.size() > 0) {
            //添加sku库存信息
            insertSkuPrice(pmsSkuStockMemberPriceList, admin, productId);
        }
        //会员价格
//        relateAndInsertList(memberPriceDao, productParam.getMemberPriceList(), productId, admin);
        //添加商品参数,添加自定义商品规格
        relateAndInsertList(productAttributeValueDao, productParam.getProductAttributeValueList(), productId, admin);
        //关联专题
        relateAndInsertList(subjectProductRelationDao, productParam.getSubjectProductRelationList(), productId);
        //关联优选
        relateAndInsertList(prefrenceAreaProductRelationDao, productParam.getPrefrenceAreaProductRelationList(), productId);

        return productId;
    }

    private String addProductSn(String productSn,Long storeId){
        PmsProductExample pmsProductExample = new PmsProductExample();
        pmsProductExample.createCriteria().andStoreIdEqualTo(storeId);
        List<PmsProduct> pmsProductList = productMapper.selectByExample(pmsProductExample);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        // for (int i = 0; i < pmsProductList.size(); i++) {
        if (StringUtils.isEmpty(productSn)) {
                StringBuilder sb = new StringBuilder();
                //日期
                sb.append(sdf.format(new Date()));
                //四位商品id
//            sb.append(String.format("%04d", productId));
                //三位索引id
                sb.append(String.format("%06d", pmsProductList.size() + 1));
                return sb.toString();
            }
//        }
      return productSn;
    }

    private void handleSkuStockCode(List<PmsSkuStockMemberPrice> skuStockList, Long productId) {
        if (CollectionUtils.isEmpty(skuStockList)) return;
        for (int i = 0; i < skuStockList.size(); i++) {
            PmsSkuStockMemberPrice skuStock = skuStockList.get(i);
            if (StringUtils.isEmpty(skuStock.getSkuCode())) {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
                StringBuilder sb = new StringBuilder();
                //日期
                sb.append(sdf.format(new Date()));
                //四位商品id
                sb.append(String.format("%04d", productId));
                //三位索引id
                sb.append(String.format("%03d", i + 1));
                skuStock.setSkuCode(sb.toString());
            }
        }
    }


    @Override
    public PmsProductResult getUpdateInfo(Long id) {
        PmsProductResult pmsProductResult =  productDao.getUpdateInfo(id);
        if(pmsProductResult.getType().equals(1)){
            PmsSkuStockExample pmsSkuStockExample = new PmsSkuStockExample();
            pmsSkuStockExample.createCriteria().andProductIdEqualTo(id);
            Long parentId = pmsSkuStockMapper.selectByExample(pmsSkuStockExample).get(0).getId();
            List<ProductDeitail>  productDeitailList = pmsCombinedProductDao.selectOrderProductDetail(parentId);
            pmsProductResult.setProductDeitailList(productDeitailList);
        }
        return pmsProductResult;
    }


    @Override
    public int update(UmsAdminDTO admin, Long id, PmsProductParam productParam) {
        int count;
        //更新商品信息
        PmsProduct product = productParam;
        product.setId(id);
        if (product.getMemberId().equals(admin.getId())) {
            if (CollectionUtils.isEmpty(productParam.getPmsCombinedProductList())) {
                product.setType(0);
            } else {
                product.setType(1);
            }
            PmsProduct pmsProduct = this.productMapper.selectByPrimaryKey(id);
            if(!pmsProduct.getVerifyStatus().equals(1)){
                product.setVerifyStatus(0);
            }
            productMapper.updateByPrimaryKeySelective(product);
            //会员价格
            PmsMemberPriceExample pmsMemberPriceExample = new PmsMemberPriceExample();
//            pmsMemberPriceExample.createCriteria().andProductIdEqualTo(id);
//            memberPriceMapper.deleteByExample(pmsMemberPriceExample);
//            relateAndInsertList(memberPriceDao, productParam.getMemberPriceList(), id, admin);
            //组合商品修改子商品

            //阶梯价格
            PmsProductLadderExample ladderExample = new PmsProductLadderExample();
            ladderExample.createCriteria().andProductIdEqualTo(id);
            productLadderMapper.deleteByExample(ladderExample);
            relateAndInsertList(productLadderDao, productParam.getProductLadderList(), id, admin);
            //满减价格
            PmsProductFullReductionExample fullReductionExample = new PmsProductFullReductionExample();
            fullReductionExample.createCriteria().andProductIdEqualTo(id);
            productFullReductionMapper.deleteByExample(fullReductionExample);
            relateAndInsertList(productFullReductionDao, productParam.getProductFullReductionList(), id, admin);
            //修改sku库存信息
            handleUpdateSkuStockList(id, productParam, admin);
            //修改商品参数,添加自定义商品规格
            PmsProductAttributeValueExample productAttributeValueExample = new PmsProductAttributeValueExample();
            productAttributeValueExample.createCriteria().andProductIdEqualTo(id);
            productAttributeValueMapper.deleteByExample(productAttributeValueExample);
            relateAndInsertList(productAttributeValueDao, productParam.getProductAttributeValueList(), id, admin);
            //关联专题
            CmsSubjectProductRelationExample subjectProductRelationExample = new CmsSubjectProductRelationExample();
            subjectProductRelationExample.createCriteria().andProductIdEqualTo(id);
            subjectProductRelationMapper.deleteByExample(subjectProductRelationExample);
            relateAndInsertList(subjectProductRelationDao, productParam.getSubjectProductRelationList(), id, admin);
            //关联优选
            CmsPrefrenceAreaProductRelationExample prefrenceAreaExample = new CmsPrefrenceAreaProductRelationExample();
            prefrenceAreaExample.createCriteria().andProductIdEqualTo(id);
            prefrenceAreaProductRelationMapper.deleteByExample(prefrenceAreaExample);
            relateAndInsertList(prefrenceAreaProductRelationDao, productParam.getPrefrenceAreaProductRelationList(), id, admin);
            count = 1;
            return count;
        } else {
            return -2;
        }
    }

    private void handleUpdateSkuStockList(Long id, PmsProductParam productParam, UmsAdminDTO admin) {
        //当前的sku信息
        List<PmsSkuStockMemberPrice> pmsSkuStockMemberPriceList = productParam.getSkuStockList();
        //当前没有sku直接删除
        if (CollUtil.isEmpty(pmsSkuStockMemberPriceList)) {
            PmsSkuStockExample skuStockExample = new PmsSkuStockExample();
            skuStockExample.createCriteria().andProductIdEqualTo(id);
            skuStockMapper.deleteByExample(skuStockExample);
            //删掉会员价,没有sku就没有会员价
            return;
        }
        //获取初始sku信息
        PmsSkuStockExample skuStockExample = new PmsSkuStockExample();
        skuStockExample.createCriteria().andProductIdEqualTo(id);
        List<PmsSkuStock> oriStuList = skuStockMapper.selectByExample(skuStockExample);
        //获取新增sku信息
        List<PmsSkuStockMemberPrice> addSkuList = pmsSkuStockMemberPriceList.stream().filter(e -> e.getId() == null).collect(Collectors.toList());
        //获取需要更新的sku信息
        List<PmsSkuStockMemberPrice> updateSkuList = pmsSkuStockMemberPriceList.stream().filter(e -> e.getId() != null).collect(Collectors.toList());
        List<Long> updateSkuIds = updateSkuList.stream().map(PmsSkuStock::getId).collect(Collectors.toList());
        Map<Long, List<PmsSkuStockMemberPrice>> updatePriceList = updateSkuList.stream().collect(Collectors.groupingBy(e -> e.getId()));
        //获取需要删除的sku信息
        List<PmsSkuStock> removeSkuList = oriStuList.stream().filter(item -> !updateSkuIds.contains(item.getId())).collect(Collectors.toList());
        handleSkuStockCode(addSkuList, id);
        handleSkuStockCode(updateSkuList, id);
        //新增sku
        if (CollUtil.isNotEmpty(addSkuList)) {
//            relateAndInsertList(skuStockDao, insertSku, id, admin);
            //新增sku和会员价格
            insertSkuPrice(addSkuList, admin, id);
        }
        //删除sku
        if (CollUtil.isNotEmpty(removeSkuList)) {
            List<Long> removeSkuIds = removeSkuList.stream().map(PmsSkuStock::getId).collect(Collectors.toList());
            PmsSkuStockExample removeExample = new PmsSkuStockExample();
            removeExample.createCriteria().andIdIn(removeSkuIds);
            skuStockMapper.deleteByExample(removeExample);
        }
        //修改sku
        if (CollUtil.isNotEmpty(updateSkuList)) {
            for (PmsSkuStock pmsSkuStock : updateSkuList) {
                skuStockMapper.updateByPrimaryKeySelective(pmsSkuStock);
                Long key = pmsSkuStock.getId();
                List<PmsSkuStockMemberPrice> pmsSkuStockMemberPrices = updatePriceList.get(key);
                //更新sku和会员价格
                updateSkuPrice(pmsSkuStockMemberPrices, admin,productParam);
            }
        }

    }

    @Override
    public List<CombinedPmsProduct> list(String currentUserName, PmsProductQueryParam productQueryParam, Integer pageSize, Integer pageNum) {
        UmsAdminDTO admin = this.umsAdminService.getAdminDTOByUserName(currentUserName);
        PmsProductExample productExample = new PmsProductExample();
        PmsProductExample.Criteria criteria = productExample.createCriteria();
        criteria.andDeleteStatusEqualTo(0);
        if (admin.getAdminType() == 1) {
            //省级管理员，可以看到他下面所有的用户的商品列表
            UmsStoreExample example = new UmsStoreExample();
            example.createCriteria().andParentIdEqualTo(admin.getId());
            List<Long> collect = this.umsStoreMapper.selectByExample(example).stream().map(UmsStore::getUserId).collect(Collectors.toList());
            criteria.andMemberIdIn(collect);
        } else if (admin.getAdminType() == 2) {
            criteria.andStoreIdEqualTo(admin.getStoreId());
        }
        if (productQueryParam.getPublishStatus() != null) {
            criteria.andPublishStatusEqualTo(productQueryParam.getPublishStatus());
        }
        if (productQueryParam.getVerifyStatus() != null) {
            criteria.andVerifyStatusEqualTo(productQueryParam.getVerifyStatus());
        }
        if (!StringUtils.isEmpty(productQueryParam.getKeyword())) {
            criteria.andNameLike("%" + productQueryParam.getKeyword() + "%");
        }
        if (!StringUtils.isEmpty(productQueryParam.getProductSn())) {
            criteria.andProductSnEqualTo(productQueryParam.getProductSn());
        }
        if (productQueryParam.getBrandId() != null) {
            criteria.andBrandIdEqualTo(productQueryParam.getBrandId());
        }
        if (productQueryParam.getProductCategoryId() != null) {
            criteria.andProductCategoryIdEqualTo(productQueryParam.getProductCategoryId());
        }
        if (productQueryParam.getType() != null) {
            criteria.andTypeEqualTo(productQueryParam.getType());
        }
        PageHelper.startPage(pageNum, pageSize);
        productExample.setOrderByClause("id desc");
        List<CombinedPmsProduct> combinedPmsProductList = productDao.selectCombinedByExample(productExample);
        if(combinedPmsProductList.size()>0){
            combinedPmsProductList.get(0).setAdminType(admin.getAdminType());
        }
        return combinedPmsProductList;
    }

    @Override
    public int updateVerifyStatus(String currentUserName, List<Long> ids, Integer verifyStatus, String detail) {
        PmsProduct product = new PmsProduct();
        product.setVerifyStatus(verifyStatus);
        PmsProductExample example = new PmsProductExample();
        example.createCriteria().andIdIn(ids);
        List<PmsProductVertifyRecord> list = new ArrayList<>();
        int count = productMapper.updateByExampleSelective(product, example);
        //修改完审核状态后插入审核记录
        for (Long id : ids) {
            PmsProductVertifyRecord record = new PmsProductVertifyRecord();
            record.setProductId(id);
            record.setCreateTime(new Date());
            record.setDetail(detail);
            record.setStatus(verifyStatus);
            record.setVertifyMan(currentUserName);
            list.add(record);
        }
        productVertifyRecordDao.insertList(list);
        return count;
    }

    @Override
    public CommonResult updatePublishStatus(List<Long> ids, Integer publishStatus) {
//        PmsProduct record = new PmsProduct();
//        record.setPublishStatus(publishStatus);
//        PmsProductExample example = new PmsProductExample();
//        example.createCriteria().andIdIn(ids);
//        return productMapper.updateByExampleSelective(record, example);
        //商品的verifyStatus为0时不能上架
//        List<Long> idsCanPublish = new ArrayList<>();//可以上架的id集合
//        Map<String,List<String>> result = new HashMap<>();//返回的map集合
//        List<String> canNotPublish = new ArrayList<>();
        for (long id : ids) {
            PmsProduct product = productMapper.selectByPrimaryKey(id);
            if (product.getVerifyStatus() == 0) {//商品未过审核
//                idsCanPublish.add(id);
                return CommonResult.failed(product.getName() + "未审核，不能上架");
            }
            if(product.getVerifyStatus() ==2){
                return CommonResult.failed(product.getName() + "审核未通过，不能上架");
            }
        }
//        result.put("notVerify",canNotPublish);
        PmsProduct record = new PmsProduct();
        record.setPublishStatus(publishStatus);
        PmsProductExample example = new PmsProductExample();
        example.createCriteria().andIdIn(ids);
        int count = productMapper.updateByExampleSelective(record, example);
        if (publishStatus.equals(0)) {
            //删除推荐表
            SmsHomeRecommendProductExample recommendProductExample = new SmsHomeRecommendProductExample();
            recommendProductExample.createCriteria().andProductIdIn(ids);
            recommendProductMapper.deleteByExample(recommendProductExample);
            //删除热门搜索表
            PmsKeywordExample keywordExample = new PmsKeywordExample();
            keywordExample.createCriteria().andProductIdIn(ids);
            keywordMapper.deleteByExample(keywordExample);
        }
        if (count > 0) {
            return CommonResult.success(count);
        } else {
            return CommonResult.failed();
        }
    }

    @Override
    public int updateRecommendStatus(List<Long> ids, Integer recommendStatus) {
        PmsProduct record = new PmsProduct();
        record.setRecommandStatus(recommendStatus);
        PmsProductExample example = new PmsProductExample();
        example.createCriteria().andIdIn(ids);
        return productMapper.updateByExampleSelective(record, example);
    }

    @Override
    public int updateNewStatus(List<Long> ids, Integer newStatus) {
        PmsProduct record = new PmsProduct();
        record.setNewStatus(newStatus);
        PmsProductExample example = new PmsProductExample();
        example.createCriteria().andIdIn(ids);
        return productMapper.updateByExampleSelective(record, example);
    }

    @Override
    public int updateDeleteStatus(List<Long> ids, Integer deleteStatus) {
        PmsProduct record = new PmsProduct();
        record.setDeleteStatus(deleteStatus);
        PmsProductExample example = new PmsProductExample();
        example.createCriteria().andIdIn(ids);
        int count = productMapper.updateByExampleSelective(record, example);
        //删除推荐表
        SmsHomeRecommendProductExample recommendProductExample = new SmsHomeRecommendProductExample();
        recommendProductExample.createCriteria().andProductIdIn(ids);
        recommendProductMapper.deleteByExample(recommendProductExample);
        //删除热门搜索表
        PmsKeywordExample keywordExample = new PmsKeywordExample();
        keywordExample.createCriteria().andProductIdIn(ids);
        keywordMapper.deleteByExample(keywordExample);
        return count;
    }

    @Override
    public List<PmsProduct> list(String currentUserName, String keyword) {
        UmsAdminDTO admin = this.umsAdminService.getAdminDTOByUserName(currentUserName);
        PmsProductExample productExample = new PmsProductExample();
        PmsProductExample.Criteria criteria = productExample.createCriteria();
        criteria.andDeleteStatusEqualTo(0);
        criteria.andStoreIdEqualTo(admin.getStoreId());
        criteria.andVerifyStatusEqualTo(1);
        criteria.andPublishStatusEqualTo(1);
        if (!StringUtils.isEmpty(keyword)) {
            criteria.andNameLike("%" + keyword + "%");
        }
        List<PmsProduct> products = productMapper.selectByExample(productExample);
        return products;
    }

    @Override
    public Long createCombined(UmsAdminDTO admin, PmsProductParam productParam) {
        Long id = this.create(admin, productParam);
        this.creatCombinedProduct(admin, productParam, id);
        return id;
    }

    /**
     * 创建组合商品
     *
     * @param admin
     * @param productParam
     * @param id
     * @author zhouboyu
     * @Date 2020年9月3日
     */
    private void creatCombinedProduct(UmsAdminDTO admin, PmsProductParam productParam, Long id) {
        PmsSkuStockExample pmsSkuStockExample = new PmsSkuStockExample();
        pmsSkuStockExample.createCriteria().andProductIdEqualTo(id);
        Long skuId = pmsSkuStockMapper.selectByExample(pmsSkuStockExample).get(0).getId();
        List<PmsCombinedProduct> pmsCombinedProductList = productParam.getPmsCombinedProductList();
        pmsCombinedProductList.forEach(e -> {
            e.setMemberId(admin.getId());
            e.setMemberUserName(admin.getUserName());
            e.setStoreId(admin.getStoreId());
            e.setParentId(skuId);
            this.pmsCombinedProductMapper.insert(e);
        });
    }

    @Override
    public int updateCombined(UmsAdminDTO admin, Long id, PmsProductParam productParam) {
        int update = this.update(admin, id, productParam);
        PmsSkuStockExample stockExample = new PmsSkuStockExample();
        stockExample.createCriteria().andProductIdEqualTo(id);
        List<PmsSkuStock> pmsSkuStocks = skuStockMapper.selectByExample(stockExample);
        PmsSkuStock pmsSkuStock = pmsSkuStocks.get(0);
        pmsSkuStock.setPrice(productParam.getPrice());
        skuStockMapper.updateByPrimaryKeySelective(pmsSkuStock);
        List<Long> collect = pmsSkuStocks.stream().map(PmsSkuStock::getId).collect(Collectors.toList());
        PmsCombinedProductExample example = new PmsCombinedProductExample();
        example.createCriteria().andParentIdIn(collect);
        int i = this.pmsCombinedProductMapper.deleteByExample(example);
        this.creatCombinedProduct(admin, productParam, id);
        return update;
    }


    /**
     * 根据商品id获取商品规格信息
     * 用于审核商品时查看
     *
     * @param id 商品id
     * @return
     * @author 孙晓亮
     * @Date 2020年9月12日
     */
    @Override
    public List<PmsSkuStock> gerProductSkuInfo(Long id) {
        List<PmsSkuStock> pmsSkuStockList = skuStockMapper.selectByProductId(id);
        return pmsSkuStockList;
    }

    /**
     * 根据商品id查询商品审核失败原因
     *
     * @param id 商品id
     * @return
     * @author 孙晓亮
     * @Data 2020年9月12日
     */
    @Override
    public PmsProductVertifyRecord getProductVertifyDetail(Long id) {
        List<PmsProductVertifyRecord> productVertifyDetail = pmsProductVertifyRecordMapper.getProductVertifyDetail(id);
        if (productVertifyDetail != null && !productVertifyDetail.isEmpty()) {
            return productVertifyDetail.get(0);
        } else {
            return null;
        }
    }

    /**
     * 查询组合商品
     *
     * @param currentUserName
     * @param productQueryParam
     * @param pageSize
     * @param pageNum
     * @return
     */
    @Override
    public List<CombinedPmsProduct> getCombinedProductList(String currentUserName, PmsProductQueryParam productQueryParam, Integer pageSize, Integer pageNum) {

        UmsAdmin admin = this.umsAdminService.getAdminByUsername(currentUserName);
        PageHelper.startPage(pageNum, pageSize);
        PmsProductExample productExample = new PmsProductExample();
        PmsProductExample.Criteria criteria = productExample.createCriteria();
        criteria.andDeleteStatusEqualTo(0);
        if (admin.getAdminType() == 1) {
            //省级管理员，可以看到他下面所有的用户的商品列表
            UmsStoreExample example = new UmsStoreExample();
            example.createCriteria().andParentIdEqualTo(admin.getId());
            List<Long> collect = this.umsStoreMapper.selectByExample(example).stream().map(UmsStore::getUserId).collect(Collectors.toList());
            criteria.andMemberIdIn(collect);
        } else if (admin.getAdminType() == 2) {
            criteria.andMemberUserNameEqualTo(currentUserName);
        }
        if (productQueryParam.getPublishStatus() != null) {
            criteria.andPublishStatusEqualTo(productQueryParam.getPublishStatus());
        }
        if (productQueryParam.getVerifyStatus() != null) {
            criteria.andVerifyStatusEqualTo(productQueryParam.getVerifyStatus());
        }
        if (!StringUtils.isEmpty(productQueryParam.getKeyword())) {
            criteria.andNameLike("%" + productQueryParam.getKeyword() + "%");
        }
        if (!StringUtils.isEmpty(productQueryParam.getProductSn())) {
            criteria.andProductSnEqualTo(productQueryParam.getProductSn());
        }
        if (productQueryParam.getBrandId() != null) {
            criteria.andBrandIdEqualTo(productQueryParam.getBrandId());
        }
        if (productQueryParam.getProductCategoryId() != null) {
            criteria.andProductCategoryIdEqualTo(productQueryParam.getProductCategoryId());
        }
        if (productQueryParam.getType() != null) {
            criteria.andTypeEqualTo(productQueryParam.getType());
        }
        List<CombinedPmsProduct> combinedPmsProductList = productDao.selectCombinedByExample(productExample);

        return combinedPmsProductList;
    }

    /**
     * 根据skuid查询商品信息
     * @param ids
     * @return
     * @author 孙晓亮
     * @Date 2020年9月16日
     */
    @Override
    public CommonResult getProductInfoBySkuId(List<Long> ids) {
        PmsSkuStockExample skuStockExample = new PmsSkuStockExample();
        skuStockExample.createCriteria().andIdIn(ids);
        List<PmsSkuStock> pmsSkuStockList = pmsSkuStockMapper.selectByExample(skuStockExample);
        List<Long> productIds = new ArrayList<>();
        pmsSkuStockList.forEach(p -> {
            productIds.add(p.getProductId());
        });
        PmsProductExample example = new PmsProductExample();
        example.createCriteria().andIdIn(productIds);
        return CommonResult.success(productMapper.selectByExample(example));
    }

//    @Override
//    public CommonPage<PmsInProductSkuDto> getProductSku(String currentUsername, String productName, Integer pageSize, Integer pageNum) {
//        PageHelper.startPage(pageNum, pageSize);
//        List<PmsInProductSkuDto> result = new ArrayList<>();
//        //获取当前登录的用户
//        UmsAdminDTO admin = umsAdminService.getAdminDTOByUserName(currentUsername);
//        //根据admin的strorage id查询商品表
//        List<PmsInProductSkuDto> pmsProductSkuDtos = skuStockDao.selectPmsSkuStockInProduct(admin.getStoreId(), productName);
//        CommonPage<PmsInProductSkuDto> pmsList = CommonPage.restPage(pmsProductSkuDtos);
//        List<PmsInProductSkuDto> list = pmsList.getList();
//        for (PmsInProductSkuDto psStock : list) {
//            PmsInProductSkuDto dto = new PmsInProductSkuDto();
//            BeanUtils.copyProperties(psStock, dto);
//            result.add(dto);
//        }
//        CommonPage<PmsInProductSkuDto> commonPage = new CommonPage();
//        BeanUtils.copyProperties(pmsList, commonPage);
//        return commonPage;
//    }

    /**
     * 查询所有出库商品列表
     */
    @Override
    public CommonPage<PmsOutProductSkuDto> getOutProductList(String currentUserName,String productName, Integer type, Integer pageSize, Integer pageNum,Integer judgeStock) {
        List<PmsOutProductSkuDto> result = new ArrayList<>();
        //获取当前登录的用户
        UmsAdminDTO admin = umsAdminService.getAdminDTOByUserName(currentUserName);
        //根据admin的strorage id查询商品表
//        if(productName != null && !"".equals(productName)){
//            productName = "%" + productName + "%";
//        }
        //用来筛选是否是组合商品和审核状态
        VeProductParam param = new VeProductParam();
        if(type == null){
            param.setVerifyStatus(1);
            param.setPublishStatus(1);
        }
        PageHelper.startPage(pageNum, pageSize);
        List<PmsOutProductSkuDto> psStockList = skuStockDao.selectPmsSkuStockOutProduct(admin.getStoreId(),productName,judgeStock,param);
        CommonPage<PmsOutProductSkuDto> pmsOutProductSkuDtoCommonPage = CommonPage.restPage(psStockList);
        List<PmsOutProductSkuDto> list1 = pmsOutProductSkuDtoCommonPage.getList();
        if (!CollectionUtils.isEmpty(list1)) {
//            List<PmsOutProductSkuDto> psStocks = list1.stream().filter(e -> e.getType() != 1).collect(Collectors.toList());
//            CommonPage<PmsOutProductSkuDto> pmsList = CommonPage.restPage(psStocks);
//            List<PmsOutProductSkuDto> list = pmsList.getList();
            for (PmsOutProductSkuDto psStock : list1) {
                PmsOutProductSkuDto dto = new PmsOutProductSkuDto();
                BeanUtils.copyProperties(psStock, dto);
                result.add(dto);
            }
        }
        CommonPage<PmsOutProductSkuDto> commonPage = new CommonPage();
        BeanUtils.copyProperties(pmsOutProductSkuDtoCommonPage, commonPage);
        commonPage.setList(result);
        return commonPage;
    }

    /**
     * 建立和插入关系表操作
     *
     * @param dao       可以操作的dao
     * @param dataList  要插入的数据
     * @param productId 建立关系的id
     */
    private void relateAndInsertList(Object dao, List dataList, Long productId, UmsAdminDTO adminDTO) {
        try {
            if (CollectionUtils.isEmpty(dataList)) return;
            for (Object item : dataList) {
                Method setId = item.getClass().getMethod("setId", Long.class);
                setId.invoke(item, (Long) null);
                Method setProductId = item.getClass().getMethod("setProductId", Long.class);
                setProductId.invoke(item, productId);
                Method setMemberId = item.getClass().getMethod("setMemberId", Long.class);
                setMemberId.invoke(item, adminDTO.getId());
                Method setMemberUserName = item.getClass().getMethod("setMemberUserName", String.class);
                setMemberUserName.invoke(item, adminDTO.getUserName());
                Method setStoreId = item.getClass().getMethod("setStoreId", Long.class);
                setStoreId.invoke(item, adminDTO.getStoreId());
            }
            Method insertList = dao.getClass().getMethod("insertList", List.class);
            insertList.invoke(dao, dataList);
        } catch (Exception e) {
            LOGGER.warn("创建产品出错:{}", e.getMessage());
            throw new RuntimeException(e.getMessage());
        }
    }

    /**
     * 建立和插入关系表操作
     * 不对store做数据隔离
     *
     * @param dao       可以操作的dao
     * @param dataList  要插入的数据
     * @param productId 建立关系的id
     */
    private void relateAndInsertList(Object dao, List dataList, Long productId) {
        try {
            if (CollectionUtils.isEmpty(dataList)) return;
            for (Object item : dataList) {
                Method setId = item.getClass().getMethod("setId", Long.class);
                setId.invoke(item, (Long) null);
                Method setProductId = item.getClass().getMethod("setProductId", Long.class);
                setProductId.invoke(item, productId);
            }
            Method insertList = dao.getClass().getMethod("insertList", List.class);
            insertList.invoke(dao, dataList);
        } catch (Exception e) {
            LOGGER.warn("创建产品出错:{}", e.getMessage());
            throw new RuntimeException(e.getMessage());
        }
    }

    /**
     * 新增sku和memberPrice表
     *
     * @param pmsSkuStockMemberPriceList sku和价格的封装
     * @param admin                      用户
     * @param productId                  商品id
     * @author 高强
     * @Date 2020年9月9日
     */
    private void insertSkuPrice(List<PmsSkuStockMemberPrice> pmsSkuStockMemberPriceList, UmsAdminDTO admin, long productId) {
        List<PmsSkuPriceLog> logs = new ArrayList<>();
        for (PmsSkuStockMemberPrice pmsSkuStockMemberPrice : pmsSkuStockMemberPriceList) {
            PmsSkuPriceLog log = new PmsSkuPriceLog();
            log.setNote("新增");
            log.setSkuId(pmsSkuStockMemberPrice.getId());
            log.setHandelUserName(admin.getUserName());
            log.setHandelUserId(admin.getId());
            log.setAddTime(new Date());
            PmsSkuStock pmsSkuStock = new PmsSkuStock();
            BeanUtils.copyProperties(pmsSkuStockMemberPrice,pmsSkuStock);
            pmsSkuStock.setMemberId(admin.getId());
            pmsSkuStock.setStoreId(admin.getStoreId());
            pmsSkuStock.setSale(0);
            pmsSkuStock.setActivityLockStock(0);
            pmsSkuStock.setMemberUserName(admin.getUserName());
            pmsSkuStock.setProductId(productId);
            log.setCurrentPrice(pmsSkuStock.getPrice());
            //添加sku库存信息
            skuStockMapper.insertSelective(pmsSkuStock);
            //会员价格
            PmsMemberPrice pmsMemberPrice = new PmsMemberPrice();
            pmsMemberPrice.setProductStockId(pmsSkuStock.getId());
            pmsMemberPrice.setMemberPrice(pmsSkuStockMemberPrice.getMemberPrice());
            pmsMemberPrice.setProductStockId(pmsSkuStock.getId());
            pmsMemberPrice.setMemberId(admin.getId());
            pmsMemberPrice.setStoreId(admin.getStoreId());
            pmsMemberPrice.setMemberUserName(admin.getUserName());
            log.setCurrentMemberPrice(pmsSkuStockMemberPrice.getMemberPrice());
            memberPriceMapper.insertSelective(pmsMemberPrice);
            logs.add(log);
        }
        if(!CollectionUtils.isEmpty(logs)){
            for (PmsSkuPriceLog l:logs) {
                this.priceLogMapper.insert(l);
            }
        }
    }

    /**
     * 更新sku和memberPrice表
     *
     * @param pmsSkuStockMemberPriceList sku和价格的封装
     * @param admin                      用户
     * @author 高强
     * @Date 2020年9月9日
     */
    private void updateSkuPrice(List<PmsSkuStockMemberPrice> pmsSkuStockMemberPriceList, UmsAdminDTO admin,PmsProductParam productParam) {
        List<PmsSkuPriceLog> logs = new ArrayList<>();
        for (PmsSkuStockMemberPrice pmsSkuStockMemberPrice : pmsSkuStockMemberPriceList) {
            PmsSkuStock pmsSkuStock = new PmsSkuStock();
            BeanUtils.copyProperties(pmsSkuStockMemberPrice,pmsSkuStock);
            if (productParam.getMemberId().equals(admin.getId())) {
                PmsSkuPriceLog log = new PmsSkuPriceLog();
                log.setNote("修改");
                log.setSkuId(pmsSkuStockMemberPrice.getId());
                log.setHandelUserName(admin.getUserName());
                log.setHandelUserId(admin.getId());
                log.setAddTime(new Date());
                pmsSkuStock.setActivityLockStock(0);
                log.setCurrentPrice(pmsSkuStock.getPrice());
                skuStockMapper.updateByPrimaryKeySelective(pmsSkuStock);//添加sku库存信息
                //会员价格
                PmsMemberPriceExample example = new PmsMemberPriceExample();
                example.createCriteria().andStoreIdEqualTo(admin.getStoreId()).andMemberIdEqualTo(admin.getId())
                        .andProductStockIdEqualTo(pmsSkuStockMemberPrice.getId());
                PmsMemberPrice memberPrice = new PmsMemberPrice();
                if (pmsSkuStockMemberPrice.getMemberPrice() == null) {
                    pmsSkuStockMemberPrice.setMemberPrice(new BigDecimal(BigInteger.ZERO));
                }
                log.setCurrentMemberPrice(pmsSkuStockMemberPrice.getMemberPrice());
                memberPrice.setMemberPrice(pmsSkuStockMemberPrice.getMemberPrice());
                memberPriceMapper.updateByExampleSelective(memberPrice,example);
                logs.add(log);
            }
        }
        if(!CollectionUtils.isEmpty(logs)){
            for (PmsSkuPriceLog log:logs) {
                this.priceLogMapper.insert(log);
            }
        }
    }


    @Override
    public CommonResult getProductByids(List<Long> ids) {
        PmsSkuStockExample skuStockExample = new PmsSkuStockExample();
        skuStockExample.createCriteria().andIdIn(ids);
        List<PmsSkuStock> pmsSkuStockList = pmsSkuStockMapper.selectByExample(skuStockExample);
        return CommonResult.success(pmsSkuStockList) ;
//        List<Long> productIds = new ArrayList<>();
//        pmsSkuStockList.forEach(p -> {
//            productIds.add(p.getProductId());
//        });
//        PmsProductExample example = new PmsProductExample();
//        example.createCriteria().andIdIn(productIds);
//        return CommonResult.success(productMapper.selectByExample(example));
    }
    /**
     * 根据主商品id查询子商品信息
     * @param id
     * @return
     */
    @Override
    public CommonResult<List<ProductDeitail>> getCombined(Long id) {
        PmsSkuStockExample pmsSkuStockExample = new PmsSkuStockExample();
        pmsSkuStockExample.createCriteria().andProductIdEqualTo(id);
        Long parentId = pmsSkuStockMapper.selectByExample(pmsSkuStockExample).get(0).getId();
        List<ProductDeitail>  productDeitailList = pmsCombinedProductDao.selectOrderProductDetail(parentId);
        return CommonResult.success(productDeitailList);
    }

    @Override
    public boolean whetherVerify(Long id) {
        PmsProduct product = productMapper.selectByPrimaryKey(id);
        Integer verifyStatus = product.getVerifyStatus();
        if (verifyStatus.equals(1)) {
            //已审核
            return true;
        }else{
            //未审核
            return false;
        }
    }

}
